﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;//引用命名空间
using Microsoft.Extensions.Logging; //日志命名空间

namespace WLW4Ceng.APIHost.AOP_面向切面_
{
    /// <summary>
    /// 自定义一次过滤器
    /// </summary>
    public class MyExceptionFilter : IExceptionFilter
    {

        private readonly ILogger<MyExceptionFilter> _logger;

        public MyExceptionFilter (ILogger<MyExceptionFilter> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 需要实现以下接口方法
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            //拿到控制器名字和方法
            string contriller = context.RouteData.Values["controller"].ToString();
            string action = context.RouteData.Values["action"].ToString();

            //可以拿到用户请求的api路径
            string api = context.HttpContext.Request.Path;

            //在方法中,处理异常 写入Nlog日志
            Exception ex = context.Exception;
            var message =$"用户访问了:{api},错误信息为:{ex.Message}\n 错误堆栈跟踪信息为:{ex.StackTrace}";
            _logger.LogError(message);//写入日志

            context.ExceptionHandled = true;//把异常标记为已处理
        }
    }
}
